package com.scilvet.reportcomposer.account;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

public class Amount implements Comparable<Amount> {

	private static final int SCALE = 2;
	
	public static final Amount ZERO = new Amount("0");
	public static final Amount ONE = new Amount("1");
	
	private BigDecimal amount;
	
	public Amount(String amount) {
		
		BigDecimal unscaledAmount = new BigDecimal(amount, MathContext.UNLIMITED);
		this.amount = unscaledAmount.setScale(SCALE, RoundingMode.HALF_UP);
	}
	
	private Amount(BigDecimal amount) {
		
		this.amount = amount.setScale(SCALE, RoundingMode.HALF_UP);
	}
	
	public BigDecimal getAmount() {
		return amount;
	}
	
	public Amount add(Amount augend) {
		
		BigDecimal result = amount.add(augend.getAmount(), MathContext.UNLIMITED);
		return new Amount(result);
	}
	
	public Amount subtract(Amount subtrahend) {
		
		BigDecimal result = amount.subtract(subtrahend.getAmount(), MathContext.UNLIMITED);
		return new Amount(result);
	}
	
	public Amount multiply(Amount multiplicand) {
		
		BigDecimal result = amount.multiply(multiplicand.getAmount(), MathContext.UNLIMITED);
		return new Amount(result);
	}
	
	public Amount divide(Amount divisor) {
		
		BigDecimal result = amount.divide(divisor.getAmount(), SCALE, RoundingMode.HALF_UP);
		return new Amount(result);
	}
	
	public Amount negate() {
		
		return new Amount(amount.negate());
	}
	
	@Override
	public String toString() {
		return amount.toString();
	}

	@Override
	public int compareTo(Amount o) {
		
		return amount.compareTo(o.getAmount());
	}
	
	@Override
	public boolean equals(Object other) {
		
		if (!(other instanceof Amount)) {
			return false;
		}
		
		return amount.equals(((Amount)other).getAmount());
	}
}
